package com.graduate.cec.exception.handler;


import com.graduate.cec.common.JsonResult;
import com.graduate.cec.common.ResponseCode;
import com.graduate.cec.exception.CecServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalControllerExceptionHandler {

    /**
     * 处理业务异常
     */
    @ExceptionHandler({CecServiceException.class})
    public JsonResult<Void> handleCecServiceException(CecServiceException e) {
        return JsonResult.failed(e.getResponseCode(), e.getMessage());
    }

    /**
     * 处理绑定异常（通过Validation框架验证请求参数时的异常）
     */
    @ExceptionHandler(BindException.class)
    public JsonResult<Void> handleBindException(BindException e) {
        log.debug("验证请求数据时出现异常：{}", e.getClass().getName());
        e.printStackTrace();
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        JsonResult<Void> result = JsonResult.failed(ResponseCode.BAD_REQUEST, message);
        log.debug("即将返回：{}", result);
        return JsonResult.failed(ResponseCode.ERR_BAD_REQUEST, e.getMessage());
    }



}